<template>
  <div class="main-body">
    <div class="load-mask" v-show="firstLoad">
      <img v-if="loadingImgUrl" :src="loadingImgUrl" @load="switchFirstLoad" alt="" />
      <van-loading v-else size="46px" color="#fde494" vertical>红包正在路上...</van-loading>
    </div>
    <div :class="{ 'new-person': isNewPerson, 'is-share': isShare }">
      <div class="banner">
        <van-swipe class="my-swipe" :autoplay="3000" indicator-color="white">
          <template v-if="info.imgs.length">
            <van-swipe-item v-for="(item, index) in info.imgs" :key="index">
              <img :src="item.imgUrl" alt="" :style="{ height: getImgHeight() }" />
            </van-swipe-item>
          </template>
          <template v-else>
            <van-swipe-item>
              <img src="../../assets/img/banner.png" alt="" />
            </van-swipe-item>
          </template>
        </van-swipe>
        <div class="expose" @click="goExpose">
          <router-link class="white" :to="{ name: 'Feedback' }">投诉举报</router-link>
        </div>
        <div class="rules" @click="showRule = true">活动说明</div>
        <div v-if="info.awardInfoFlag" class="recent">
          <template v-if="info.awardInfoList && info.awardInfoList.length">
            <van-swipe style="height: 24px" vertical :autoplay="3000" :show-indicators="false">
              <van-swipe-item v-for="(item, index) in info.awardInfoList" :key="index">
                <div class="record">
                  <van-image round width="1.3rem" height="1.3rem" :src="item.userAvatar" />
                  &nbsp;{{ item.userName }}领取活动现金红包{{ item.actualMoney }}元
                </div>
              </van-swipe-item>
            </van-swipe>
          </template>
        </div>
      </div>
      <!-- 从配置页面点击活动分享按钮进入 -->
      <template v-if="isShare">
        <div class="pop-package red-bg">
          <div class="head">
            <img class="img" src="../../assets/img/share-title.png" alt="" />
            <div class="activity-name share-name">-&nbsp;{{ info.mainTitle }}&nbsp;-</div>
          </div>
          <!--<div class="flex-cb mt-10">
            <div class="golden fs-40">
              <b>{{ redEnvelope.redAmount }}</b>
            </div>
            <div class="white">&nbsp;元</div>
          </div>-->
          <div class="golden align-center mt-20">累计奖励{{ info.cumulativeAmount || 0 }}元，已放入微信零钱</div>
          <div class="flex-blank">&nbsp;</div>
          <div class="white align-center mt-20">
            <b>每邀{{ info.inviteThreshold }}人，可拆一次</b>
          </div>
          <van-row class="avatar-list mt-10" :justify="info.inviteThreshold > 1 ? 'space-between' : 'center'">
            <van-col v-for="(item, index) in receiveList" :key="index" span="8">
              <van-image round width="15vw" height="15vw" :src="item.receiveUserAvatar" loading-icon="plus" />
              <div class="text golden">{{ item.receiveUserName || '待邀请' }}</div>
            </van-col>
          </van-row>
          <div class="flex-blank">&nbsp;</div>
          <div class="invite-btn mt-20" @click="shareHandle">&nbsp;</div>
          <div class="align-center mt-20 mb-10">
            <a @click="goInviteList" class="invite-list-btn golden">邀请列表</a>
          </div>
        </div>
      </template>
      <!-- C 端新用户在微信中打开 -->
      <template v-else-if="isNewPerson">
        <div class="package new-person">
          <div style="line-height: 0">
            <img class="img" src="../../assets/img/new-person-bg.png" alt="" />
          </div>
          <div class="activity-name">{{ info.mainTitle }}</div>
          <div class="amount-range" style="line-height: 0">
            <img class="img" src="../../assets/img/amount-range.png" alt="" />
          </div>
          <div class="qrcode-box">
            <van-row class="officer-info">
              <van-col span="4" class="center">
                <van-image round fit="cover" width="11.2vw" height="11.2vw" src="https://img.yzcdn.cn/vant/cat.jpeg" />
              </van-col>
              <van-col span="20">
                <p class="flex-sc white" style="margin: 0 0 8px">
                  {{ info.companyName }}&nbsp;
                  <img class="label" src="../../assets/img/label.png" alt="" />
                </p>
                <div class="welcome-text">
                  {{ info.welcomeMsg }}
                  <span class="iconfont icon-hand-point yellow"></span>
                  <span class="iconfont icon-hand-point yellow"></span>
                  <span class="iconfont icon-hand-point yellow"></span>
                  <span class="iconfont icon-hand-point yellow"></span>
                  <span class="iconfont icon-hand-point yellow"></span>
                  <span class="iconfont icon-hand-point yellow"></span>
                  <!--<mark class="unicode" data-char-info="U+261F: WHITE DOWN POINTING INDEX">☟</mark>-->
                  <!--<mark class="unicode" data-char-info="U+261F: WHITE DOWN POINTING INDEX">☟</mark>-->
                  <!--<mark class="unicode" data-char-info="U+261F: WHITE DOWN POINTING INDEX">☟</mark>-->
                  <!--<mark class="unicode" data-char-info="U+261F: WHITE DOWN POINTING INDEX">☟</mark>-->
                  <!--<mark class="unicode" data-char-info="U+261F: WHITE DOWN POINTING INDEX">☟</mark>-->
                  <!--<mark class="unicode" data-char-info="U+261F: WHITE DOWN POINTING INDEX">☟</mark>-->
                </div>
              </van-col>
            </van-row>
            <div class="group">
              <van-image width="42vw" height="42vw" :src="info.qrCode" />
              <div class="golden align-center mt-10">长按识别二维码</div>
              <div class="golden align-center mt-5">添加企业福利官领微信</div>
            </div>
            <div class="corp-info">
              <van-row justify="center" align="center">
                <van-image width="6.27vw" height="6.27vw" radius="5" :src="info.companyLogoUrl" />
                <b class="fs-12 white">&nbsp;{{ info.companyName }}</b>
              </van-row>
            </div>
          </div>
          <div class="support-info">
            <div class="flex-center mb-10">
              -&nbsp;此红包由&nbsp;
              <van-image
                v-if="info.companyLogoUrl"
                round
                fit="cover"
                width="5.07vw"
                height="5.07vw"
                :src="info.companyLogoUrl"
              />
              &nbsp;{{ info.companyName }}提供&nbsp;-
            </div>
            <p class="golden align-center">
              -&nbsp;<router-link class="golden" :to="{ name: 'CustomerService' }">实证科技仅提供技术支持 </router-link
              >&nbsp;-
            </p>
          </div>
        </div>
      </template>
      <!-- 默认界面 -->
      <template v-else>
        <div class="main-box">
          <div class="package">
            <div style="line-height: 0; position: relative">
              <img class="img" src="../../assets/img/hongbao.jpg" alt="" />

              <div class="activity-name">{{ info.mainTitle }}</div>
              <div class="receive-num">{{ info.receiveAmount }}人已获得红包</div>
              <div class="coin-btn" @click="onOpenClick">&nbsp;</div>
              <div class="reset-num">红包剩余{{ info.redAmount }}个</div>
            </div>
            <!--<div v-if="info.expand && info.expand.sexFlag" class="white">
              <p>红包领取资格：</p>
              <p v-if="info.expand.sexFlag && info.expand.sexLimits.length">
                限定性别：{{info.expand.sexLimits.join()}}
              </p>
            </div>-->
            <div class="support-info activity-limit">
              <div v-if="info.expand && info.expand.sexFlag" class="white mb-20 plr-5w">
                <p class="fs-18">红包领取资格：</p>
                <p v-if="info.expand.sexFlag && info.expand.sexLimits.length">
                  限定性别：{{ info.expand.sexLimits.join() }}
                </p>
              </div>
              <div class="flex-center mb-10">
                -&nbsp;此红包由&nbsp;
                <van-image
                  v-if="info.companyLogoUrl"
                  round
                  fit="cover"
                  width="5.07vw"
                  height="5.07vw"
                  :src="info.companyLogoUrl"
                />
                &nbsp;{{ info.companyName }}提供&nbsp;-
              </div>
              <p class="golden align-center">
                -&nbsp;<router-link class="golden" :to="{ name: 'CustomerService' }"
                  >实证科技仅提供技术支持 </router-link
                >&nbsp;-
              </p>
            </div>
          </div>
        </div>
      </template>
    </div>

    <!-- 活动说明 -->
    <van-overlay :show="showRule" @click="showRule = false">
      <div class="popup-wrapper">
        <div class="block" @click.stop>
          <div class="pop-package red-bg">
            <div class="head">
              <img class="img" src="../../assets/img/share-title.png" alt="" />
              <div class="activity-name">-&nbsp;活动说明&nbsp;-</div>
            </div>
            <div class="rules-box" v-html="info.description"></div>
            <div class="align-center mt-20 mb-10 mt-20 golden">活动最终解释权归{{ info.companyName }}所有</div>
          </div>
        </div>
        <div class="close-btn" @click="showRule = false">&nbsp;</div>
      </div>
    </van-overlay>

    <!-- 活动结束 -->
    <van-overlay :show="showOver" @click="showOver = false">
      <div class="popup-wrapper">
        <div class="block" @click.stop>
          <div class="head">
            <img
              v-if="info.imgs.length"
              class="img"
              :src="info.imgs[0].imgUrl"
              alt=""
              :style="{ height: getImgHeight(0.83) }"
            />
            <img v-else class="img" src="../../assets/img/banner.png" alt="" :style="{ height: getImgHeight(0.83) }" />
          </div>
          <div class="pop-package red-bg">
            <div class="head">
              <img class="img" src="../../assets/img/share-title.png" alt="" />
              <div class="activity-name">-&nbsp;{{ info.mainTitle }}&nbsp;-</div>
            </div>
            <div class="flex-blank">&nbsp;</div>
            <div class="group">
              <div class="golden align-center fs-30">活动已结束</div>
              <div class="golden align-center fs-13 mt-10">累计奖励 {{ info.cumulativeAmount || 0 }} 元</div>
            </div>
            <div class="flex-blank">&nbsp;</div>
            <div class="group">
              <div class="golden align-center fs-30">
                <i class="iconfont icon-dengpao"></i>
              </div>
              <div class="golden align-center fs-13 mt-10">敬请在{{ info.companyName }}客服处留意更多活动哦~</div>
            </div>
            <div class="flex-blank">&nbsp;</div>
            <div class="group">
              <div class="invite-btn gray mt-40">&nbsp;</div>
              <div class="align-center mt-20 mb-10">
                <a @click="goInviteList" class="invite-list-btn golden">邀请列表</a>
              </div>
            </div>
          </div>
        </div>
        <div class="close-btn" @click="showOver = false">&nbsp;</div>
      </div>
    </van-overlay>

    <!-- 分享 -->
    <van-overlay :show="showInvite" @click="showInvite = false">
      <div class="popup-wrapper">
        <div class="block" @click.stop>
          <div class="head">
            <img
              v-if="info.imgs.length"
              class="img"
              :src="info.imgs[0].imgUrl"
              alt=""
              :style="{ height: getImgHeight(0.83) }"
            />
            <img v-else class="img" src="../../assets/img/banner.png" alt="" :style="{ height: getImgHeight(0.83) }" />
          </div>
          <div class="pop-package red-bg">
            <div class="head">
              <img class="img" src="../../assets/img/share-title.png" alt="" />
              <div class="activity-name">-&nbsp;{{ info.mainTitle }}&nbsp;-</div>
            </div>
            <div v-if="redEnvelope.redAmount" class="flex-cb mt-10">
              <div class="golden fs-40">
                <b>{{ redEnvelope.redAmount }}</b>
              </div>
              <div class="white">&nbsp;元</div>
            </div>
            <div v-if="redEnvelope.redAmount" class="golden align-center mt-5">
              累计奖励{{ info.cumulativeAmount || 0 }}元，已放入微信零钱
            </div>
            <div v-else class="golden align-center mt-20">
              累计奖励{{ info.cumulativeAmount || 0 }}元，已放入微信零钱
            </div>
            <div class="white align-center mt-20">
              <b>每邀{{ info.inviteThreshold }}人，可拆一次</b>
            </div>
            <van-row class="avatar-list mt-10" :justify="info.inviteThreshold > 2 ? 'space-between' : 'center'">
              <van-col v-for="(item, index) in receiveList" :key="index" span="8">
                <van-image round width="15vw" height="15vw" :src="item.receiveUserAvatar" loading-icon="plus" />
                <div class="text golden">{{ item.receiveUserName || '待邀请' }}</div>
              </van-col>
            </van-row>
            <div class="invite-btn mt-20" @click="shareHandle">&nbsp;</div>
            <div class="align-center mt-20 mb-10">
              <a @click="goInviteList" class="invite-list-btn golden">邀请列表</a>
            </div>
          </div>
        </div>
        <div class="close-btn" @click="showInvite = false">&nbsp;</div>
      </div>
    </van-overlay>

    <!-- 分享达标，拆红包 -->
    <van-overlay :show="showOpen" @click="showOpen = false">
      <div class="popup-wrapper">
        <div class="block" @click.stop>
          <div class="head">
            <img
              v-if="info.imgs.length"
              class="img"
              :src="info.imgs[0].imgUrl"
              alt=""
              :style="{ height: getImgHeight(0.83) }"
            />
            <img v-else class="img" src="../../assets/img/banner.png" alt="" :style="{ height: getImgHeight(0.83) }" />
          </div>
          <div class="pop-package">
            <div style="line-height: 0">
              <img class="img" src="../../assets/img/open-bg.png" alt="" />
            </div>
            <div class="activity-name">-&nbsp;{{ info.mainTitle }}&nbsp;-</div>
            <div class="bonus flex-center golden">
              <div class="fs-30">
                {{ redEnvelope.redAmount }}
              </div>
              <div class="fs-24">&nbsp;元</div>
            </div>
            <div class="sum golden align-center fs-12">
              累计奖励{{ redEnvelope.cumulativeAmount || 0 }}元，已放入微信零钱
            </div>
            <div class="coin-btn" @click="onOpenClick">&nbsp;</div>
            <div class="reset-num">红包剩余{{ info.redAmount }}个</div>
          </div>
        </div>
        <div class="close-btn" @click="showOpen = false">&nbsp;</div>
      </div>
    </van-overlay>

    <!-- 海报弹框 -->
    <van-overlay :show="showGenerate" @click="showGenerate = false">
      <div class="popup-wrapper">
        <div v-if="!!shareImgURL" class="block" @click.stop style="line-height: 0">
          <img class="img" :src="shareImgURL" alt="" style="object-fit: cover" />
        </div>
        <div class="close-btn" @click="showGenerate = false">&nbsp;</div>
      </div>
    </van-overlay>

    <!-- 微信分享操作指引 -->
    <van-overlay :show="showShareTips" @click="showShareTips = false">
      <div class="share-tips" @click.stop>
        <img class="img" src="../../assets/img/share-tip.png" alt="" />
      </div>
    </van-overlay>

    <!-- 海报源 -->
    <!--<div id="haibao" class="block">
      <div class="head">
        <img v-if="info.imgs.length" class="img" :src="info.imgs[0].imgUrl" alt="" />
        <img v-else class="img" src="../../assets/img/banner.png" alt="" />
      </div>
      <div class="pop-package">
        <div style="line-height: 0">
          <img class="img" src="../../assets/img/share-bg.png" alt="" />
        </div>
        <div class="activity-name">-&nbsp;{{ info.mainTitle }}&nbsp;-</div>
        <div class="avatar">&nbsp;</div>
        &lt;!&ndash;<van-image round width="100%" height="100%" fit="cover" :src="wxUserInfo.avatar" />&ndash;&gt;
        <div class="receive-num golden">{{ wxUserInfo.name }}已领取</div>
        <div id="share-box" class="foot">
          <div class="left-group">
            <div class="golden mb-10">{{ info.receiveAmount }}人已领取</div>
            <div class="golden">长按或扫描二维码领取</div>
          </div>
          <img class="code-box" :src="QRCodeUrl" alt="" />
        </div>
      </div>
    </div>-->

    <div class="generate-btn" @click="generateImg">生成海报</div>
  </div>
</template>

<script>
import { reactive, toRefs, onBeforeMount, onUnmounted, onMounted, watch } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import wx from 'wx';
import { injectWx } from '@/utils';
import { activityInfo, generateShareImg, getPacketInfo, shareActivity } from '@/api/activity';
import { Swipe, SwipeItem, Popup, Button, Col, Row, Dialog, Icon, Overlay, Loading, Image as VanImage } from 'vant';
const genderMap = {
  // 0-未知 1-男性 2-女性
  0: '未知',
  1: '男性',
  2: '女性',
};
function useActivity(props, fn) {
  const state = reactive({
    info: {
      imgs: [],
      companyLogoUrl: '',
    }, // 活动信息,
    firstLoad: window.isWX, // 首次加载
    loadingImgUrl: '', // h5加载图片url
    unOpenList: [], // 待拆红包列表
    receiveList: [], // 邀请红包门槛达成前-已邀请列表
    QRCodeUrl: '', // 二维码链接
    shareURL: '', // 分享链接
  });
  const loadingTime = 3000; // 加载中界面显示时间
  // 构造分享链接，使用静默授权，用户无感知
  const createShareUrl = () => {
    let { userId, userType } = state.info.inviteUser;
    // 不记录跨越的分享关系
    // 还未添加客服，不是系统用户。分享人使用从页面URL带入的原始分享人信息
    // if (!props.sysUserInfo) {
    //   userId = props.inviteId;
    //   userType = props.inviteType;
    // }
    // 因为企业微信分享时会丢失参数，这里把两个参数拼接在一起
    let inviteInfo = `${/^\d+$/.test(userId) ? userId : ''}_${
      /^\d+$/.test(userType) ? userType : ''
    }_${new Date().getTime()}`;
    state.shareURL = `${location.protocol}//${location.host}${process.env.VUE_APP_PUBLIC_PATH}redEnvelope/${props.businessId}/${props.activityId}/${inviteInfo}`;
    // let url = `${location.protocol}//${location.host}${process.env.VUE_APP_PUBLIC_PATH}redEnvelope/${props.businessId}/${props.activityId}/${inviteInfo}`;
    console.log('createShareUrl shareURL: ', state.shareURL);
    // url = window.encodeURIComponent(url);
    // state.shareURL = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${process.env.VUE_APP_AppID}&redirect_uri=${url}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect`;
  };
  const recordShareCount = () => {
    shareActivity(props.route.params.activityId, props.inviteId, props.inviteType);
  };
  const registerShareFn = () => {
    const data = state.info;
    wx.checkJsApi({
      jsApiList: [
        'onMenuShareAppMessage',
        'onMenuShareTimeline',
        'updateAppMessageShareData',
        'updateTimelineShareData',
      ], // 需要检测的JS接口列表，所有JS接口列表见附录2,
      success: function (res) {
        // companyLogoUrl
        console.log('data.companyLogoUrl: ', data.companyLogoUrl);
        console.log('从微信分享到微信，不构造授权链接: ', state.shareURL);
        const getParams = (txt) => {
          let obj = {
            title: data.pageTitle, // 分享标题
            desc: data.mainTitle, // 分享描述
            link: state.shareURL, // 分享链接；在微信上分享时，该链接的域名必须与企业某个应用的可信域名一致
            imgUrl: data.companyLogoUrl, // 分享图标
            success: () => {
              console.log(`${txt} is triggered, 分享计数 +1`);
              recordShareCount();
            },
          };
          if (/onMenuShareAppMessage|onMenuShareTimeline/.test(txt)) {
            // 因为只有部分手机会触发这两个API回调，为了避免数据异常，不处理回调事件
            delete obj.success;
          }
          return obj;
        };
        // 以键值对的形式返回，可用的api值true，不可用为false
        // 如：{"checkResult":{"onMenuShareAppMessage":true},"errMsg":"checkJsApi:ok"}
        if (res.checkResult && res.checkResult.onMenuShareAppMessage) {
          wx.onMenuShareAppMessage(getParams('wx.onMenuShareAppMessage'));
        }
        if (res.checkResult && res.checkResult.onMenuShareTimeline) {
          // 微信文档中，这个API的参数没有 desc
          wx.onMenuShareTimeline(getParams('wx.onMenuShareTimeline'));
        }
        // 微信新API，会造成分享计数异常。被分享人每次打开页面都会触发计数
        if (res.checkResult && res.checkResult.updateAppMessageShareData) {
          wx.updateAppMessageShareData(getParams('wx.updateAppMessageShareData'));
        }

        if (res.checkResult && res.checkResult.updateAppMessageShareData) {
          wx.updateAppMessageShareData(getParams('wx.updateAppMessageShareData'));
        }
      },
    });
  };
  const onInviteBtnClick = () => {
    const data = state.info;
    let url = window.encodeURIComponent(state.shareURL);
    url = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${process.env.VUE_APP_AppID}&redirect_uri=${url}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect`;
    console.log('从企业微信分享到微信，构造授权链接：', url);
    // 自定义转发到微信
    wx.invoke(
      'shareWechatMessage',
      {
        title: data.pageTitle, // 分享标题
        desc: data.mainTitle, // 分享描述
        link: url, // 分享链接；在微信上分享时，该链接的域名必须与企业某个应用的可信域名一致
        imgUrl: data.companyLogoUrl, // 分享封面
      },
      function (res) {
        if (res.err_msg === 'shareWechatMessage:ok') {
          recordShareCount();
        }
      }
    );
  };
  const switchFirstLoad = () => {
    window.setTimeout(() => {
      state.firstLoad = false;
    }, loadingTime);
  };
  const getActivityInfo = async (...args) => {
    try {
      const res = await fn(...args);
      if (res.code === 200) {
        const data = res.data || {};
        // 拼接出图片完整路径
        let imgHead = `${location.protocol}//${location.host}`;
        data.imgs = (data.imgs || []).map((x) => ({
          ...x,
          imgUrl: `${imgHead}${x.imgUrl}`,
        }));
        // 处理活动说明中的换行符
        data.description = data.description.replace(/\n/g, '</p><p class="rules-text">');
        data.description = `<p class="rules-text">${data.description}</p>`;
        data.expand.sexLimits = (data.expand.sexLimits || []).map((x) => genderMap[x]);
        state.info = data;
        state.unOpenList = data.unOpenList || [];
        // 分享没达标时添加空对象，使头像占位区显示
        let arr = new Array(data.inviteThreshold);
        arr.fill({});
        state.receiveList = (data.receiveList || []).concat(arr).slice(0, data.inviteThreshold);
        state.loadingImgUrl = data.expand && data.expand.loadingImgUrl ? data.expand.loadingImgUrl : '';
        document.getElementsByTagName('title')[0].innerHTML = data.pageTitle || window.oldTitle;
        if (state.firstLoad && !state.loadingImgUrl) {
          switchFirstLoad();
        }
        createShareUrl();
        registerShareFn();
      } else {
        state.info = {};
        state.unOpenList = [];
        state.receiveList = [];
        state.loadingImgUrl = '';
        document.getElementsByTagName('title')[0].innerHTML = window.oldTitle;
      }
    } catch (err) {
      document.getElementsByTagName('title')[0].innerHTML = window.oldTitle;
      console.log(err);
    }
  };
  return {
    ...toRefs(state),
    onInviteBtnClick,
    switchFirstLoad,
    getActivityInfo,
  };
}

export default {
  name: 'RedEnvelope',
  components: {
    [Row.name]: Row,
    [Col.name]: Col,
    [Icon.name]: Icon,
    [Popup.name]: Popup,
    [Swipe.name]: Swipe,
    [Button.name]: Button,
    [Overlay.name]: Overlay,
    [Loading.name]: Loading,
    [VanImage.name]: VanImage,
    [SwipeItem.name]: SwipeItem,
    [Dialog.Component.name]: Dialog.Component,
  },
  props: {
    activityId: String,
    businessId: String,
  },
  setup(props) {
    const router = useRouter();
    const route = useRoute();
    const wxUserInfo = window.wxUserInfo;
    const sysUserInfo = window.sysUserInfo;
    // 从页面URL带入的原始分享人信息
    let [inviteId, inviteType, timestamp] = (route.params.invite || '').split('_');
    inviteId = inviteId || '';
    inviteType = inviteType || '';
    const state = reactive({
      isShare: route.query.isShare === '1' && /wxwork/i.test(window.navigator.userAgent), // 是否展示分享界面
      showRule: false, // 活动规则弹框开关
      showOver: false, // 活动已结束弹框开关
      showInvite: false, // 邀请弹框开关, 邀请数量不够，没有红包可拆
      showOpen: false, // 分享达标，拆红包弹框开关
      showGenerate: false, // 生成海报弹框开关
      showShareTips: false, // 分享提示弹框开关
      isNewPerson: !sysUserInfo, // 新人进入
      inviteId: inviteId || '',
      inviteType: inviteType || '',
      oldTitle: '', // 旧的页面标题,
      imgUrl: '', // 海报base64,
      shareImgURL: '', // 分享海报图片地址
      wxUserInfo,
    });

    const {
      info,
      status,
      QRCodeUrl,
      firstLoad,
      shareURL,
      loadingImgUrl,
      unOpenList,
      receiveList,
      getActivityInfo,
      switchFirstLoad,
      onInviteBtnClick,
    } = useActivity(
      { sysUserInfo, inviteId, inviteType, route, activityId: props.activityId, businessId: props.businessId },
      (params) => activityInfo(params)
    );
    watch(
      () => info.value.status,
      (status, prevStatus) => {
        if (status !== prevStatus) {
          // 1=编辑中，2=进行中/已发布，3=已结束/已关闭，4=违规叫停
          state.showOver = status && (status === 3 || status === 4); //活动已结束
        }
      }
    );
    if (route.query.isShare === '1' && /wxwork/i.test(window.navigator.userAgent)) {
      watch(
        () => unOpenList.value,
        (list, prevList) => {
          // 如果有红包可以拆的时候，优先显示拆
          state.isShare = list.length <= 0;
        }
      );
    }

    const redEnvelope = reactive({
      cumulativeAmount: 0,
      redAmount: 0,
    });
    const shareHandle = () => {
      const isWX = /MicroMessenger/i.test(window.navigator.userAgent) && !/wxwork/i.test(window.navigator.userAgent);
      if (isWX) {
        state.showShareTips = true;
        state.showInvite = false;
      } else {
        onInviteBtnClick();
      }
    };
    const onOpenClick = async () => {
      if (info.value.status === 2 && unOpenList.value.length > 0) {
        const packet = unOpenList.value.pop();
        getPacketInfo({
          activityId: props.activityId,
          packetId: packet.packetId,
          packetType: packet.packetType,
        }).then(
          async (res) => {
            if (res.code === 200) {
              redEnvelope.cumulativeAmount = res.data.cumulativeAmount || 0;
              redEnvelope.redAmount = res.data.redAmount || 0;
            } else {
              redEnvelope.cumulativeAmount = 0;
              redEnvelope.redAmount = 0;
            }
            state.showOpen = info.value.status === 2 && unOpenList.value.length > 0;
            state.showInvite = info.value.status === 2 && unOpenList.value.length <= 0;
            state.showOver = info.value.status === 3 || info.value.status === 4; // 1=编辑中，2=进行中/已发布，3=已结束/已关闭，4=违规叫停
            console.log('redEnvelope', redEnvelope);
            await getActivityInfo({
              activityId: props.activityId,
              inviteId: state.inviteId,
              inviteType: state.inviteType,
              openId: wxUserInfo.openId,
              unionId: wxUserInfo.unionid || wxUserInfo.nickName || wxUserInfo.nickname || wxUserInfo.userId,
              avatar: wxUserInfo.headimgurl || wxUserInfo.headImgUrl || wxUserInfo.avatar,
            });
          },
          (res) => {
            if (res.code === 6051) {
              Dialog.alert({
                title: '未实名认证',
                message: res.msg,
                // '因微信规则，非实名用户账号不可发放，请先去实名认证，方可参与后续活动。', // res.msg
                theme: 'round-button',
              }).then(() => {
                // on close
              });
            }
            if (res.code === 5050) {
              Dialog.alert({
                title: '拆红包须知',
                message: res.msg,
                // '不好意思，您的性别/地区不符合我们的活动要求，无法直接给您一个新人红包。\n\n但您可以通过邀请符合活动要求的朋友领取现金红包，满足邀请人数后您自己也可以获得拆邀请红包的机会。',
                theme: 'round-button',
                confirmButtonText: '邀请好友拆红包',
              }).then(() => {
                // on close
                shareHandle();
              });
            }
          }
        );
      } else {
        state.showOpen = false;
        state.showInvite = info.value.status === 2 && unOpenList.value.length <= 0; // 邀请数量不够，没有红包可拆
        state.showOver = info.value.status === 3 || info.value.status === 4; // 1=编辑中，2=进行中/已发布，3=已结束/已关闭，4=违规叫停
      }
    };

    const goInviteList = (e) => {
      e.preventDefault();
      e.stopPropagation();
      // router.push({ name: 'InviteList', params: { activityId: props.activityId } });
      router.push(`/redEnvelope/invite/${props.activityId}`);
    };
    const generateImg = async () => {
      if (!state.shareImgURL) {
        const res = await generateShareImg({ activityId: props.activityId, qrCodeContent: shareURL.value });
        state.shareImgURL = res.data.imgPath; // shareImgURL
        state.showGenerate = true;
      } else {
        state.showGenerate = true;
      }
    };
    onBeforeMount(() => {
      window.oldTitle = document.getElementsByTagName('title')[0].innerHTML;
      getActivityInfo({
        activityId: props.activityId,
        inviteId: state.inviteId,
        inviteType: state.inviteType,
        openId: wxUserInfo.openId,
        unionId: wxUserInfo.unionid || wxUserInfo.nickName || wxUserInfo.nickname || wxUserInfo.userId,
        avatar: wxUserInfo.headimgurl || wxUserInfo.headImgUrl || wxUserInfo.avatar,
      });
    });
    onMounted(() => {
      let arr = ['hideOptionMenu', 'hideMenuItems', 'hideAllNonBaseMenuItem'];
      if (window.isWX) {
        arr = [
          'hideMenuItems',
          'hideAllNonBaseMenuItem',
          'updateAppMessageShareData',
          'updateTimelineShareData',
          'onMenuShareTimeline',
          'onMenuShareAppMessage',
        ];
      }
      injectWx(arr).then((res) => {
        if (res) {
          if (/wxwork/i.test(window.navigator.userAgent)) {
            console.log('A');
            wx.hideOptionMenu();
            wx.hideMenuItems({
              menuList: [
                'menuItem:setFont', // 没有生效
                'menuItem:exposeArticle', // 没有生效
                'menuItem:share:appMessage',
              ],
            });
            wx.hideAllNonBaseMenuItem();
          }
          if (window.isWX) {
            console.log('B');
            wx.hideMenuItems({
              menuList: [
                'menuItem:setFont', // 没有生效
                'menuItem:copyUrl',
                'menuItem:exposeArticle', // 没有生效
                'menuItem:share:qq',
                'menuItem:share:QZone',
                'menuItem:share:email',
                'menuItem:share:facebook',
                'menuItem:share:weiboApp',
                'menuItem:openWithSafari',
                'menuItem:openWithQQBrowser',
              ],
            });
            // wx.hideAllNonBaseMenuItem();
          }
        }
      });
    });
    onUnmounted(() => {
      document.getElementsByTagName('title')[0].innerHTML = window.oldTitle;
    });
    const getImgHeight = (zoom) => {
      const baseWidth = document.body.clientWidth;
      const scale = 0.56;
      if (zoom) {
        return `${baseWidth * zoom * scale}px`;
      }
      return `${baseWidth * scale}px`;
    };
    return {
      ...toRefs(state),
      info,
      status,
      QRCodeUrl,
      unOpenList,
      receiveList,
      firstLoad,
      loadingImgUrl,
      switchFirstLoad,
      getActivityInfo,
      onInviteBtnClick,
      redEnvelope,
      shareHandle,
      onOpenClick,
      goInviteList,
      generateImg,
      getImgHeight,
    };
  },
};
</script>
<style lang="less" scoped>
.is-share {
  background-color: #ff2731;
  overflow: scroll;
  height: 100vh;
}
.main-body {
  :deep(.van-overlay) {
    overflow-y: scroll;
    //pointer-events: bounding-box;
  }
}
.main-box {
  position: relative;
  width: 100%;
  background-color: #f94f35;
  overflow: hidden;
}

.img {
  width: 100%;
  height: auto;
}

.canvas {
  border: 0;
  display: block;
  margin: 0;
  box-sizing: border-box;
  position: fixed;
  left: -200%;
  top: 0;
}

.popup-wrapper {
  display: flex;
  align-items: center;
  justify-content: space-around;
  flex-direction: column;
  //height: 100%;
  width: 83%;
  height: auto;
  min-height: 100%;
  margin: 0 auto;
  //padding: 10px 0;
}
.popup-wrapper .block {
  margin: 10px 0;
}
.popup-wrapper .close-btn {
  margin: 10px 0;
}
.share-tips {
  width: 100%;
  overflow: hidden;

  & > img {
    width: 100%;
    height: auto;
  }
}

.block {
  width: 100%;
  position: relative;
  overflow: hidden;
  border-radius: 20px;
}

.block .head {
  margin-bottom: -1px;
  line-height: 0;
}

.close-btn {
  //width: 40px;
  width: 100%;
  height: 40px;
  background: url('../../assets/img/close-btn.png') center no-repeat;
  background-size: contain;
  overflow: hidden;
}

#haibao {
  border-radius: 0;
  position: fixed;
  top: 0;
  left: -100%;
  width: 83%;
}

.package,
.pop-package {
  position: relative;
  overflow: hidden;
}

.activity-name {
  position: absolute;
  top: 5.8%;
  width: 100%;
  font-size: 16px;
  font-weight: 600;
  color: #ffffff;
  text-align: center;
}

.receive-num {
  position: absolute;
  top: 14.9%;
  width: 100%;
  font-size: 12px;
  color: #ffffff;
  text-align: center;
}

.coin-btn {
  position: absolute;
  top: 36.7%;
  left: 50%;
  margin-left: -42px;
  width: 85px; /*22.67%;*/
  height: 85px;
  border-radius: 85px;
  //background: url("../../assets/img/coin.png") center no-repeat;
  //background-size: cover;
}

.reset-num {
  position: absolute;
  top: 63%;
  width: 100%;
  font-size: 13px;
  color: #ffffff;
  text-align: center;
}

.support-info {
  position: absolute;
  bottom: 6.38%;
  width: 100%;
  font-size: 14px;
  color: #ffffff;
}

.support-info.activity-limit {
  position: relative;
  bottom: unset;
  margin-top: -23.47vw;
  padding-bottom: 10vw;
}

.package.new-person {
  .activity-name {
    top: 3.6%;
  }

  .amount-range {
    position: absolute;
    top: 10.85%;
    left: 0;
    width: 100%;
  }

  .support-info {
    bottom: 5.38%;
  }

  .label {
    width: 14.4vw;
    height: auto;
  }

  .qrcode-box {
    position: absolute;
    top: 20%;
    margin-left: 5.3%;
    width: 89.33%;
    height: 64.07%;
    padding: 15px;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    align-items: center;
    border: solid 1px #ffeb9c;
    border-radius: 5px;
    background: transparent;

    .officer-info {
      width: 100%;
    }

    .welcome-text {
      position: relative;
      display: flex;
      background: white;
      border-radius: 5px;
      min-height: 2em;
      width: 100%;
      font-size: 12px;
      padding: 4px;
      letter-spacing: 1px;
      overflow: hidden;
      display: -webkit-box;
      text-overflow: ellipsis;
      -webkit-line-clamp: 4; /*要显示的行数*/
      -webkit-box-orient: vertical;

      &:before {
        display: block;
        content: ' ';
        position: absolute;
        left: 0;
        top: 12px;
        width: 10px;
        height: 10px;
        background: #fff;
        transform: translate(-100%, -50%);
      }
    }
  }
}

.pop-package {
  .activity-name {
    top: 3.5%;
    font-weight: normal;
  }

  .receive-num {
    top: auto;
    bottom: 35%;
  }

  .avatar {
    position: absolute;
    width: 62px;
    height: 62px;
    top: 44.2%;
    left: 39.5%;
    background-color: green;
    overflow: hidden;
    border-radius: 31px;
  }

  .foot {
    position: absolute;
    bottom: 8%;
    width: 100%;
    padding: 0 24px;
    overflow: hidden;
    display: flex;
    justify-content: space-between;

    & > .left-group {
      display: flex;
      flex-direction: column;
      justify-content: flex-end;
      font-size: 13px;
      line-height: 1.2;
    }
  }

  .code-box {
    width: 80px;
    height: 80px;
    float: right;
  }

  .bonus {
    position: absolute;
    top: 19%;
    left: 0;
    width: 100%;
  }

  .sum {
    position: absolute;
    top: 37%;
    left: 0;
    width: 100%;
  }

  .coin-btn {
    top: 46.2%;
    margin-left: -43px;
  }

  .reset-num {
    top: 79%;
  }

  &.red-bg {
    background-color: #ff2731;
    display: flex;
    flex-direction: column;

    .head {
      position: relative;

      .activity-name {
        top: 67%;

        &.share-name {
          top: 38%;
        }
      }
    }

    .invite-btn {
      width: 68.94%;
      height: 50px;
      background: url('../../assets/img/invite-btn.png') center no-repeat;
      background-size: cover;
      border-radius: 25px;
      margin: 20px auto 0 auto;
    }

    .invite-btn:not(.gray) {
      box-shadow: 2px 12px 5px -6px #00000059;
    }

    .invite-btn.gray {
      background-image: url('../../assets/img/invite-btn-gray.png');
    }

    .invite-list-btn {
      text-decoration: underline;
    }

    .avatar-list {
      width: 100%;
    }

    .avatar-list .van-col {
      text-align: center;
    }

    .avatar-list .van-col .text {
      margin-top: 5px;
      color: #fff;
      font-size: 12px;
      text-align: center;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
    }
  }
}

.rules,
.record,
.expose,
.generate-btn {
  height: 24px;
  line-height: 26px;
  padding: 0 10px 0 15px;
  border-radius: 12px 0 0 12px;
  background: rgba(0, 0, 0, 0.4);
  color: #fff;
  font-size: 12px;
}

.rules-box {
  margin-top: 20px;
}

.rules,
.expose,
.generate-btn {
  position: absolute;
  top: 10px;
  right: 0;
}

.rules {
  top: 50px;
}

.generate-btn {
  top: 48%;
  //background: linear-gradient(to right, #fde494, #fde494);
  background: #fde494;
  color: #f84a40;
}

.banner {
  position: relative;

  .recent {
    position: absolute;
    left: 0;
    top: 10px;
    width: 64%;
    height: 130px;
    overflow: hidden;
    background: transparent;
    box-sizing: border-box;

    .record {
      width: auto;
      max-width: 100%;
      border-radius: 12px;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
      margin-bottom: 10px;
      box-sizing: border-box;
      display: flex;
      align-items: center;

      :deep(.van-image) {
        flex: 0 0 1.3rem;
      }
    }
  }
}

.my-swipe .van-swipe-item {
  height: auto;
  line-height: 0;
  text-align: center;

  & > img {
    width: 100%;
    height: auto;
  }
}

.load-mask {
  position: fixed;
  width: 100%;
  height: 100%;
  left: 0;
  top: 0;
  z-index: 99;
  background-color: #ff2731;
  display: flex;
  justify-content: center;
  align-items: center;

  img {
    flex: 1 1 auto;
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
}
</style>
